{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "name": "generalized_contrastive_loss.ipynb",
      "provenance": [
        {
          "file_id": "1gP6orB_1mRXdMTrKi8xvL06_5f3u9Nw2",
          "timestamp": 1604290125178
        }
      ],
      "collapsed_sections": [],
      "last_runtime": {
        "build_target": "//learning/deepmind/dm_python:dm_notebook3",
        "kind": "private"
      }
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    }
  },
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "pEAjCLI8QCjU"
      },
      "source": [
        "##### Copyright 2020 Google LLC.\n",
        "\n",
        "Licensed under the Apache License, Version 2.0 (the \"License\");\n",
        "you may not use this file except in compliance with the License.\n",
        "You may obtain a copy of the License at\n",
        "\n",
        "https://www.apache.org/licenses/LICENSE-2.0\n",
        "\n",
        "Unless required by applicable law or agreed to in writing, software\n",
        "distributed under the License is distributed on an \"AS IS\" BASIS,\n",
        "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
        "See the License for the specific language governing permissions and\n",
        "limitations under the License."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "2lCKaZSM2Ac0"
      },
      "source": [
        "## Generalized contrastive loss\n",
        "\n",
        "This notebook contains implementation of generalized contrastive loss from ***Intriguing Properties of Contrastive Losses***."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "0amaY7x4wgGr",
        "cellView": "both"
      },
      "source": [
        "def generalized_contrastive_loss(\n",
        "    hidden1,\n",
        "    hidden2,\n",
        "    lambda_weight=1.0,\n",
        "    temperature=1.0,\n",
        "    dist='normal',\n",
        "    hidden_norm=True,\n",
        "    loss_scaling=1.0):\n",
        "  \"\"\"Generalized contrastive loss.\n",
        "\n",
        "  Both hidden1 and hidden2 should have shape of (n, d).\n",
        "\n",
        "  Configurations to get following losses:\n",
        "  * decoupled NT-Xent loss: set dist='logsumexp', hidden_norm=True\n",
        "  * SWD with normal distribution: set dist='normal', hidden_norm=False\n",
        "  * SWD with uniform hypersphere: set dist='normal', hidden_norm=True\n",
        "  * SWD with uniform hypercube: set dist='uniform', hidden_norm=False\n",
        "  \"\"\"\n",
        "  hidden_dim = hidden1.shape[-1]  # get hidden dimension\n",
        "  if hidden_norm:\n",
        "    hidden1 = tf.math.l2_normalize(hidden1, -1)\n",
        "    hidden2 = tf.math.l2_normalize(hidden2, -1)\n",
        "  loss_align = tf.reduce_mean((hidden1 - hidden2)**2) / 2.\n",
        "  hiddens = tf.concat([hidden1, hidden2], 0)\n",
        "  if dist == 'logsumexp':\n",
        "    loss_dist_match = get_logsumexp_loss(hiddens, temperature)\n",
        "  else:\n",
        "    initializer = tf.keras.initializers.Orthogonal()\n",
        "    rand_w = initializer([hidden_dim, hidden_dim])\n",
        "    loss_dist_match = get_swd_loss(hiddens, rand_w,\n",
        "                            prior=dist,\n",
        "                            hidden_norm=hidden_norm)\n",
        "  return loss_scaling * (loss_align + lambda_weight * loss_dist_match)"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "gsXaxQOrJxHe"
      },
      "source": [
        "# Utilities for loss implementation.\n",
        "\n",
        "\n",
        "def get_logsumexp_loss(states, temperature):\n",
        "  scores = tf.matmul(states, states, transpose_b=True)  # (bsz, bsz)\n",
        "  bias = tf.math.log(tf.cast(tf.shape(states)[1], tf.float32))  # a constant\n",
        "  return  tf.reduce_mean(\n",
        "      tf.math.reduce_logsumexp(scores / temperature, 1) - bias)\n",
        "\n",
        "\n",
        "def sort(x):\n",
        "  \"\"\"Returns the matrix x where each row is sorted (ascending).\"\"\"\n",
        "  xshape = tf.shape(x)\n",
        "  rank = tf.reduce_sum(\n",
        "      tf.cast(tf.expand_dims(x, 2) > tf.expand_dims(x, 1), tf.int32), axis=2)\n",
        "  rank_inv = tf.einsum(\n",
        "      'dbc,c->db',\n",
        "      tf.transpose(tf.cast(tf.one_hot(rank, xshape[1]), tf.float32), [0, 2, 1]),\n",
        "      tf.range(xshape[1], dtype='float32'))  # (dim, bsz)\n",
        "  x = tf.gather(x, tf.cast(rank_inv, tf.int32), axis=-1, batch_dims=-1)\n",
        "  return x\n",
        "\n",
        "\n",
        "def get_swd_loss(states, rand_w, prior='normal', stddev=1., hidden_norm=True):\n",
        "  states_shape = tf.shape(states)\n",
        "  states = tf.matmul(states, rand_w)\n",
        "  states_t = sort(tf.transpose(states))  # (dim, bsz)\n",
        "\n",
        "  if prior == 'normal':\n",
        "    states_prior = tf.random.normal(states_shape, mean=0, stddev=stddev)\n",
        "  elif prior == 'uniform':\n",
        "    states_prior = tf.random.uniform(states_shape, -stddev, stddev)\n",
        "  else:\n",
        "    raise ValueError('Unknown prior {}'.format(prior))\n",
        "  if hidden_norm:\n",
        "    states_prior = tf.math.l2_normalize(states_prior, -1)\n",
        "  states_prior = tf.matmul(states_prior, rand_w)\n",
        "  states_prior_t = sort(tf.transpose(states_prior))  # (dim, bsz)\n",
        "\n",
        "  return tf.reduce_mean((states_prior_t - states_t)**2)"
      ],
      "execution_count": null,
      "outputs": []
    }
  ]
}